<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./jquery.js"></script>
  </head>
  <body>
    <button>添加</button>
    <div>
      用户名：<input type="text" id="username" /><br />
      密 &nbsp;&nbsp;码：<input type="password" id="pwd" /><br />
      <button id="btn">提交</button>
    </div>
    <table border="1" style="width: 800px">
      <thead>
        <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>密 码</th>
          <th>创建时间</th>
          <th>操 作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </body>
  <script>
    var allData = [],
      userid
    $(function () {
      getUserList()
      $('#btn').click(function () {
        var username = $('#username').val(),
          password = $('#pwd').val(),
          url = 'http://test2022.com/user/add'
        var data = {
          username: username,
          pwd: password,
        }
        if (userid) {
          url = 'http://test2022.com/user/edit'
          data.id = userid
        }
        $.ajax({
          url: url,
          method: 'POST',
          dataType: 'json',
          data: data,
          success: function (res) {
            if (res.code == 200) {
              alert(res.msg)
              userid = false
              getUserList()
            } else {
              alert(res.msg)
            }
          },
        })
      })
    })
    function getUserList() {
      $.ajax({
        url: 'http://test2022.com/user',
        method: 'GET',
        dataType: 'json',
        success: function (res) {
          allData = res.data
          var strHtml = ''
          for (let i in allData) {
            strHtml += `<tr>
                          <td>${allData[i].id}</td>
                          <td>${allData[i].username}</td>
                          <td>${allData[i].pwd}</td>
                          <td>${allData[i].create_at}</td>
                          <td><button onclick="edit(${i})">edit</button>|<button onclick="del(${res.data[i].id})">del</button></td>
                        </tr>`
          }
          $('tbody').html(strHtml)
        },
      })
    }
    function edit(index) {
      //回显数据到表单内
      var userinfo = allData[index]
      $('#username').val(userinfo.username)
      $('#pwd').val(userinfo.pwd)
      userid = userinfo.id
    }
    function del(id) {
      $.ajax({
        url: 'http://test2022.com/user/del/' + id,
        method: 'GET',
        dataType: 'json',
        success: function (res) {
          if (res.code == 200) {
            alert(res.msg)
            getUserList()
          } else {
            alert(res.msg)
          }
        },
      })
    }
  </script>
</html>
